﻿using System;
using System.Threading;

namespace SharpDepend.Shared
{
    internal class ThreadManager : IThreadManager
    {
        class ThreadWP8 : IThread
        {
            private Delegate mAction;
            private Thread mThread;
            private string mName;
            
            public ThreadWP8(string name, Delegate action)
            {
                mName = name;
                mAction = action;
            }

            public void Start()
            {
                mThread = new Thread(new ThreadStart(delegate()
                {
                    try
                    {
                        mAction.DynamicInvoke();
                    }
                    catch (Exception error)
                    {
                        SharpDepend.Log.Error(this, error);
                        throw;
                    }
                }));
                mThread.Name = mName;
                mThread.Start();
            }

            public void Join()
            {
                mThread.Join();
            }

            public override string ToString()
            {
                return "Sharpdepend.Thread (" + mName + ")";
            }
        }

        public IThread CreateThread(string name, Delegate action)
        {
            return new ThreadWP8(name, action);
        }

        public void RunThread(string name, Delegate method)
        {
            IThread thread = CreateThread(name, method);
            thread.Start();
        }

        public void Sleep(int milliseconds)
        {
            Thread.Sleep(milliseconds);
        }
    }
}
